/**
 * 
 */
package com.acc.softmgr.common.genertor.gen;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.velocity.VelocityContext;

import com.acc.softmgr.common.genertor.bean.ColumnData;
import com.acc.softmgr.common.genertor.utils.CodeResourceUtil;
import com.acc.softmgr.common.genertor.utils.CommUtil;
import com.acc.softmgr.common.genertor.utils.PageParserUtil;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @content 生成Controller
 * 
 * @date 2017年5月20日
 * 
 * @author OprCalf
 * 
 */
public class GenerateController extends BaseGenerate {

	public void genController(String tableName, String pckPath, String controllerPath) throws SQLException {
		String className = CommUtil.formatTableNameToClassName(tableName);
		String classNameLower = className.substring(0, 1).toLowerCase() + className.substring(1, className.length());

		List<ColumnData> dataList = createBean.getColumnDatas(tableName);

		VelocityContext context = new VelocityContext();
		context.put("basePackage", CodeResourceUtil.basePackage);
		context.put("commonPackage", CodeResourceUtil.commonPackage);
		context.put("className", className);
		context.put("classNameLower", classNameLower);
		context.put("createDate", new Date());

		JSONObject json = initPrimaryKey(dataList);
		context.put("priColumnName", json.get("priColumnName"));
		context.put("priFormatColumnName", json.get("priFormatColumnName"));
		context.put("priColumnType", json.get("priColumnType"));
		context.put("priDataType", json.get("priDataType"));

		PageParserUtil.WriterPage(context, "ControllerTemplate.ftl", pckPath, controllerPath);
	}

	// 初始化主键信息
	private JSONObject initPrimaryKey(List<ColumnData> dataList) {
		JSONObject json = new JSONObject();
		for (ColumnData d : dataList) {
			if ("PRI".equals(d.getColumnKey().toUpperCase())) {
				try {
					json.put("priColumnName", d.getColumnName());// 数据库字段名称
					json.put("priFormatColumnName", d.getFormatColumnName());// JAVA字段名称
					json.put("priColumnType", d.getColumnType());// 数据库原有属性
					json.put("priDataType", d.getDataType());// JAVA属性
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		return json;
	}
}
